package com.ionehe.group.common.uaa.ex.domain.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.ionehe.group.common.io.Response;
import com.ionehe.group.common.uaa.ex.convert.FunctionConvert;
import com.ionehe.group.common.uaa.ex.model.UaaCustomerFunction;
import com.ionehe.group.common.uaa.ex.model.UaaFunction;
import com.ionehe.group.common.uaa.ex.model.UaaRoleFunction;
import com.ionehe.group.common.uaa.ex.model.UaaUserRole;
import com.ionehe.group.common.uaa.ex.dto.FunctionDetailDTO;
import com.ionehe.group.common.uaa.ex.dto.UserInfoDTO;
import com.ionehe.group.common.uaa.ex.enums.UserType;
import com.ionehe.group.common.uaa.ex.dao.CustomerFunctionDao;
import com.ionehe.group.common.uaa.ex.dao.FunctionDao;
import com.ionehe.group.common.uaa.ex.dao.RoleFunctionDao;
import com.ionehe.group.common.uaa.ex.dao.UserRoleDao;
import com.ionehe.group.common.uaa.ex.domain.service.CustomerFunctionReadService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @USER:秀
 * @DATE: 2020/12/2
 * @PROJECT_NAME: general-permissions
 * @Description 客户功能服务
 **/
@Service
@Slf4j
public class CustomerFunctionReadServiceImpl implements CustomerFunctionReadService {
    @Autowired(required = false)
    private CustomerFunctionDao customerFunctionDao;
    @Autowired(required = false)
    private FunctionDao functionDao;
    @Resource
    private UserRoleDao userRoleDao;
    @Resource
    private RoleFunctionDao roleFunctionDao;
    @Autowired(required = false)
    private FunctionConvert functionConvert;

    /**
     * 根据客户id获取功能树
     * @param userInfoDTO
     * @return
     */
    @Override
    public Response<List<FunctionDetailDTO>> getFunctionTree(UserInfoDTO userInfoDTO) {
        List<Long> functionIdList;
        // 管理员
        if (Objects.equals(userInfoDTO.getType(), UserType.ADMIN.getValue())) {
            //查询客户关联权限
            Long customerId = userInfoDTO.getCustomerId();
            UaaCustomerFunction customerFunctionQuery = new UaaCustomerFunction();
            customerFunctionQuery.setCustomerId(customerId);

            List<UaaCustomerFunction> customerFunctionList = customerFunctionDao.select(customerFunctionQuery);

            if(CollectionUtils.isEmpty(customerFunctionList)){
                return Response.yes(new ArrayList());
            }

            functionIdList = customerFunctionList.stream().map(UaaCustomerFunction::getFunctionId).collect(Collectors.toList());
        } else {
            // 非管理员
            UaaUserRole userRole = new UaaUserRole();
            userRole.setUserId(userInfoDTO.getId());
            List<UaaUserRole> userRoleList = userRoleDao.select(userRole);

            if (CollUtil.isEmpty(userRoleList)) {
                return Response.yes(Collections.emptyList());
            }

            // 角色下的权限集合
            List<Long> roleList = userRoleList.stream().map(UaaUserRole::getRoleId).collect(Collectors.toList());
            Example example = new Example(UaaRoleFunction.class);
            example.createCriteria().andIn("roleId", roleList);

            List<UaaRoleFunction> roleFunctionList = roleFunctionDao.selectByExample(example);

            functionIdList = roleFunctionList.stream().map(UaaRoleFunction::getFunctionId).collect(Collectors.toList());
        }

        //查询客户拥有权限
        List<UaaFunction> functionList = functionDao.selectByIdList(functionIdList);
        Map<Long, List<UaaFunction>> functionMap = new HashMap<>();
        functionList.forEach(function -> {
            List<UaaFunction> functions = functionMap.get(function.getPid());
            if(CollectionUtils.isEmpty(functions)){
                functions = new ArrayList();
                functionMap.put(function.getPid(), functions);
            }
            functions.add(function);
        });

        //查询level=1的功能
        List<UaaFunction> baseFunctionList = functionList.stream().filter(function -> function.getLevel() == 1).collect(Collectors.toList());

        if (CollUtil.isEmpty(baseFunctionList)) {
            baseFunctionList = functionList.stream().filter(function -> function.getLevel() == 2).collect(Collectors.toList());
        }

        //递归组装树结构
        return Response.yes(recursiveFunction(functionConvert.dolist2dto(baseFunctionList), functionMap));
    }

    /**
     * 递归获取功能树
     * @param functionDetailTree
     * @param functionMap
     * @return
     */
    private List<FunctionDetailDTO> recursiveFunction(List<FunctionDetailDTO> functionDetailTree, Map<Long, List<UaaFunction>> functionMap){
        for(FunctionDetailDTO functionDetailDTO : functionDetailTree){
            Long id = functionDetailDTO.getId();

            //找到子功能
            List<UaaFunction> childFunctionList = functionMap.get(id);

            //不为空，则递归赋值
            if(!CollectionUtils.isEmpty(childFunctionList)){
                List<FunctionDetailDTO> childFunctionDetailDTOList = functionConvert.dolist2dto(childFunctionList);
                functionDetailDTO.setChildren(childFunctionDetailDTOList);
                recursiveFunction(childFunctionDetailDTOList, functionMap);
            }
        }
        return functionDetailTree;
    }

}
